import Vue from "vue"
import VueRouter from "vue-router"

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "/user",
  },
  {
    path: "/user",
    component: () => import("src/layouts/UserLayout.vue"),
    children: [
      {
        path: "/user",
        redirect: "/user/login",
      },
      {
        path: "/user/login",
        name: "Login",
        component: () => import("src/views/user/Login.vue"),
      },
      {
        path: "/user/register",
        name: "Register",
        component: () =>
          import("src/views/user/Register.vue"),
      },
    ],
  },
  {
    path: "/app",
    component: () => import("src/layouts/AppLayout.vue"),
    children: [
      {
        path: "/app",
        redirect: "/app/chat",
      },
      {
        path: "/app/chat",
        component: () => import("src/views/app/Chat.vue"),
      },
      {
        path: "/app/address-book",
        component: () =>
          import("src/views/app/AddressBook.vue"),
      },
      {
        path: "/app/find",
        component: () => import("src/views/app/Find.vue"),
      },
      {
        path: "/app/mine",
        component: () => import("src/views/app/Mine.vue"),
      },
    ],
  },
  {
    path: "/mine/setting",
    component: () => import("src/views/mine/Setting.vue"),
  },
  {
    path: "/chat/chat-room",
    component: () => import("src/views/chat/ChatRoom.vue"),
  },
  {
    path: "/chat/chat-info",
    component: () => import("src/views/chat/ChatInfo.vue"),
  },
  {
    path: "/chat/add",
    component: () => import("src/views/chat/Add.vue"),
  },
]

const router = new VueRouter({
  routes,
})

import shareStore from "src/store/shareStore.js"

router.beforeEach((to, from, next) => {
  if (
    to.name !== "Login" &&
    to.name !== "Register" &&
    !shareStore.state.userId
  ) {
    next({ path: "/user/login" })
  } else {
    next()
  }
})

router.beforeEach((to, from, next) => {
  if (to.name === "Login" && shareStore.state.userId) {
    next({ path: "/app" })
  } else {
    next()
  }
})

export default router
